﻿using System.Windows;
using System.Windows.Controls;

namespace MultiLanguage.Infrastructure
{
    // focus on a text box will select all text
    public static class MouseDownExtension
    {
        #region MouseDownSelectAll (Attached DependencyProperty)
        public static readonly DependencyProperty MouseDownSelectAllProperty =
            DependencyProperty.RegisterAttached("MouseDownSelectAll", 
            typeof (string), typeof (MouseDownExtension),
                new PropertyMetadata(OnMouseDownSelectAllChanged));
        public static void SetMouseDownSelectAll(DependencyObject o, string value)
        {
            o.SetValue(MouseDownSelectAllProperty, value);
        }
        public static string GetMouseDownSelectAll(DependencyObject o)
        {
            return (string) o.GetValue(MouseDownSelectAllProperty);
        }
        private static void OnMouseDownSelectAllChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var tb = d as TextBox;
            if (tb != null)
            {
                tb.PreviewMouseDown += (s, a) =>
                {
                    if (!tb.IsKeyboardFocusWithin)
                    {
                        tb.Focus();
                        tb.SelectAll();
                        a.Handled = true;
                    }
                };
                tb.Focus();
                tb.SelectAll();
                tb.CaretIndex = 0;
            }
        }
        #endregion
    }
}